package com.server.tools.http_exception;

import com.server.tools.Code;
import com.server.tools.ProtoBufTools;
import com.server.tools.PublicUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class ExceptionAdvice {

    /**
     * 业务层异常
     * @param ex 收到的异常对象
     * @return 返回给前端数据
     */
    @ExceptionHandler
    public ResponseEntity<byte[]> doBusinessException(BusinessException ex){
        log.error("业务异常：",ex);
        return PublicUtils.setProtobufHeader(ProtoBufTools.getResponseClass(ex.getCode(), ex.getMessage()));
    }

    /**
     * 系统异常
     * @param ex 收到的异常对象
     * @return 返回给前端数据
     */
    @ExceptionHandler
    public ResponseEntity<byte[]> doSystemException(SystemException ex){
        log.error("系统异常：",ex);
        return PublicUtils.setProtobufHeader(ProtoBufTools.getResponseClass(ex.getCode(), ex.getMessage()));
    }

    /**
     * 其他异常
     * @param ex 收到的异常对象
     * @return 返回给前端数据
     */
    @ExceptionHandler
    public ResponseEntity<byte[]> doException(Exception ex){
        log.error("未知异常：",ex);
        return PublicUtils.setProtobufHeader(ProtoBufTools.getResponseClass(Code.UNKNOWN_EXCEPTION, ex.getMessage()));
    }
}
